﻿using System.IO;
using System.IO.Pipes;

namespace AccumulateApp.Helper
{
    /// <summary>
    /// This class is used to send and receive messages between two processes.
    /// 进程间通信
    /// </summary>
    public class ProcessMessageHelper
    {
        /// <summary>
        /// This event is used to notify the client that a message has been received.
        /// </summary>
        public static Action<string> OnMessageReceived;

        /// <summary>
        /// This method is used to start the server to receive messages.
        /// </summary>
        public static async void StartServer()
        {
            while (true)
            {
                using (var server = new NamedPipeServerStream("AzureAITest"))
                {
                    await server.WaitForConnectionAsync();
                    using (var reader = new StreamReader(server))
                    {
                        string message = await reader.ReadToEndAsync();
                        OnMessageReceived?.Invoke(message);
                    }
                }
            }
        }

        /// <summary>
        /// This method is used to send a message to the server.
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static async Task SendMessageAsync(string message)
        {
            using (var client = new NamedPipeClientStream("EmailTestTool"))
            {
                await client.ConnectAsync();
                using (var writer = new StreamWriter(client))
                {
                    await writer.WriteAsync(message);
                }
            }
        }
    }
}
